import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { VideoTagEntity } from '../entities/video-tag.entity'
import { CreateVideoTagDto } from '../dto/create-video-tag.dto'
import { UpdateVideoTagDto } from '../dto/update-video-tag.dto'
import { QueryVideoTagDto } from '../dto/query-video-tag.dto'

@Injectable()
export class VideoTagService {
  constructor(
    @InjectRepository(VideoTagEntity)
    private readonly videoTagRepository: Repository<VideoTagEntity>,
  ) {}

  async create(createVideoTagDto: CreateVideoTagDto) {
    const videoTag = this.videoTagRepository.create(createVideoTagDto)
    return await this.videoTagRepository.save(videoTag)
  }

  async findAll(queryVideoTagDto: QueryVideoTagDto) {
    const { tagName } = queryVideoTagDto
    const queryBuilder = this.videoTagRepository.createQueryBuilder('videoTag')
      .where('videoTag.isDelete = :isDelete', { isDelete: 0 })

    if (tagName) {
      queryBuilder.andWhere('videoTag.tagName LIKE :tagName', { tagName: `%${tagName}%` })
    }

    return await queryBuilder.getMany()
  }

  async findOne(id: number) {
    return await this.videoTagRepository.findOne({ where: { id, isDelete: 0 } })
  }

  async update(id: number, updateVideoTagDto: UpdateVideoTagDto) {
    const videoTag = await this.findOne(id)
    if (!videoTag) {
      return null
    }

    Object.assign(videoTag, updateVideoTagDto)
    return await this.videoTagRepository.save(videoTag)
  }

  async remove(id: number) {
    const videoTag = await this.findOne(id)
    if (!videoTag) {
      return null
    }

    videoTag.isDelete = 1
    return await this.videoTagRepository.save(videoTag)
  }
}
